package com.example.demo.limit.redis;

import com.example.demo.limit.LimitService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author lyc
 * @date 2019/6/11.
 */
@Slf4j
@Service
public class RedissonLimitServicesImpl implements LimitService {

    @Autowired(required = false)
    private RedissonClient redisson;

    ExecutorService exec = Executors.newCachedThreadPool();// 线程池

    @Override
    public void limit() {
        RSemaphore semaphore = redisson.getSemaphore("semaphore");
        semaphore.trySetPermits(10);
        log.info("有效：{}",semaphore.availablePermits());
        for (int i = 0; i <100 ; i++) {
            final int no = i;
            exec.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        if(semaphore.tryAcquire(1, TimeUnit.SECONDS)){
                            try {
                                log.info("处理业务{}",no);
                                Thread.sleep((long) (Math.random() * 10000));
                            }finally {
                                semaphore.release(1);
                            }
                        }else {
                            log.info("拒绝业务{}",no);
                        }
                    } catch (InterruptedException e) {
                        log.error("error:{}",e);
                    }
                }
            });
        }


    }
}